import {Component, OnInit, Output, EventEmitter, Input} from '@angular/core';
import {fadeIn} from "../../animate";
import {Training} from "../Training";
import {TrainingService} from "../../my-service/training.service";
import {NzMessageService} from 'ng-zorro-antd';
import {UtilService} from "../../my-service/util.service";

@Component({
  selector: 'app-add-test',
  templateUrl: './add-test.component.html',
  styleUrls: ['./add-test.component.css'],
  animations: [fadeIn]
})
export class AddTestComponent implements OnInit {
  @Output() onCloseAdd = new EventEmitter<any>();
  @Input() userGuid: string;
  @Input() training: Training;
  @Input() isClassAdd:boolean; //从班级详情页进行添加
  @Input() classGuid:string;//班级Guid
  projectName='wt';
  listOfOption = [];
  listOfTagOptions = null; //获取选择的班级的Index
  inviteCode = null;//邀请码
  trainingName = '';//训练名称
  trainingDesc = '';//训练描述
  inviteCodeLength = 5;//邀请码长度
  isLimitClass = false;//是否限定班级的选择
  getRosteList(userGuid, vaild, state,training) {
    this.trainingService.getRosterList(userGuid, vaild, state).then(res => {
      if (res.status == 1) {
        this.listOfOption = res.data;
        this.listOfOption.unshift({ClassName: '匿名模式'});
      }
      if (training) {
        if (training.classGuid && training.classGuid !== 'null') {
          //修改的为非匿名班级
          for (let i = 0; i < this.listOfOption.length; i++) {
            if (training.classGuid == this.listOfOption[i].PK_ClassGuid) {
              this.listOfTagOptions = i;
              break;
            }
          }
        } else {
          //修改的为匿名班级
          this.listOfTagOptions = 0;
        }
      }
    })
    /*修改的时候对应班级所选择的索引*/

  };

  constructor(private trainingService: TrainingService,
              private msg: NzMessageService,
              private utilService:UtilService
  ) {
  }

  ngOnInit() {
    if(!this.isClassAdd){
      //新增
      this.getRosteList(this.userGuid, 0, null,this.training);//没过期且没被删除的班级
      /*修改*/
      if (this.training) {
        this.trainingName = this.training.name;
        this.trainingDesc = this.training.desc;
        this.inviteCode = this.training.inviteCode;
      }
    }else {
      /*从班级页面进入新增，限制花名册的选择*/
      if(!this.training){
        let training = new Training(null,null,null,null,null,true,null,this.classGuid);
        this.isLimitClass = true;
        this.getRosteList(this.userGuid,0,null,training);
      }else {
        /*从班级页面修改*/
        this.isLimitClass = true;
        this.getRosteList(this.userGuid,0,null,this.training);
        this.trainingName = this.training.name;
        this.trainingDesc = this.training.desc;
        this.inviteCode = this.training.inviteCode;
      }

    }

  }

  onClose() {
    this.onCloseAdd.emit(false);
  }

  /*随机生成二维码*/
  createInviteCode() {
    this.inviteCode = (Math.random() * Date.now() / 100000).toFixed(0);
    if (this.inviteCode.length > this.inviteCodeLength) {
      this.inviteCode = this.inviteCode.toString().slice(this.inviteCode.length - this.inviteCodeLength);
    } else if (this.inviteCode.length < this.inviteCodeLength) {
      for (let i = 0; i < this.inviteCodeLength - this.inviteCode.length; i++) {
        this.inviteCode = '' + i;
      }
    }
  }

  /*创建训练*/
  createTraining() {
    let createTime = this.utilService.getCurrentTime();
    if (!this.trainingName) {
      this.msg.warning('训练名字不能为空');
      return
    }
    if (!this.trainingDesc) {
      this.msg.warning('训练描述不能为空');
      return
    }
    if(!this.listOfTagOptions){
      this.msg.warning('请选择测试班级');
      return;
    }
    if (this.training) {
      //测试修改
      this.training.name = this.trainingName;
      this.training.desc = this.trainingDesc;
      this.training.creater = this.userGuid;
      if (this.listOfTagOptions[0] === 0) {
        //修改成为匿名模式
        this.training.className = null;
        this.training.classGuid = null;
      } else {
        //非匿名模式
        this.training.className = this.listOfOption[this.listOfTagOptions].ClassName;
        this.training.classGuid = this.listOfOption[this.listOfTagOptions].PK_ClassGuid;
      }
      this.trainingService.modifyTrainingById(this.training).then(res => {
        if (res.status == 1) {
           if(this.training.inviteCodeGuid){
             this.trainingService.modifyInviteCodeTitle(this.training.name,this.training.inviteCodeGuid).then(res=>{
               if(res.status==1){
                 this.msg.success('修改训练成功');
                 this.onCloseAdd.emit(this.training);
                 this.training=null;
               }
             })
           }else {
             this.msg.success('修改训练成功');
             this.onCloseAdd.emit(this.training);
             this.training=null;
           }
        } else {
          this.msg.error('修改训练失败,请稍后再试');
          return;
        }
      });
    } else {
      //创建测试
      let training = null;
      let classGuid = null;
      let className = null;
      if (this.listOfTagOptions[0] === 0||this.listOfTagOptions==0) {
        training = new Training(null, this.trainingName, this.trainingDesc, this.userGuid, this.inviteCode, true,createTime);
        training.updateTime(createTime);
        //匿名模式
      } else {
        className = this.listOfTagOptions[0]?(this.listOfOption[this.listOfTagOptions[0]].ClassName):this.listOfOption[this.listOfTagOptions].ClassName;
        classGuid = this.listOfTagOptions[0]?(this.listOfOption[this.listOfTagOptions[0]].PK_ClassGuid):this.listOfOption[this.listOfTagOptions].PK_ClassGuid;
        training = new Training(null, this.trainingName, this.trainingDesc, this.userGuid, this.inviteCode, true,createTime,null,className,classGuid);
        training.updateTime(createTime);
      }
      this.trainingService.createTraining(training).then(res => {
        if (res.status == 1) {
          this.msg.success('创建训练成功');
          training.id = res.data;
          let endTime = new Date();
          endTime.setMonth(endTime.getMonth() + 6); //设置结束时间为6个月以后
          let LibQuery=`;className=${className};classID=${classGuid}`;
          let data={
            projectName:this.projectName,
            guid:training.id,
            FK_ClassGuid:training.classGuid,
            Title:this.trainingName,
            endTime,
            LibQuery
          };
          this.trainingService.createCode(data).then(res=>{
            if(res.status==1){
              training.inviteCode = res.code;
              training.codeEnd=false;
              this.onCloseAdd.emit(training);
              training=null;
            }
          });
        } else {
          this.msg.error('创建训练失败，请稍后再试');
          return;
        }
      })
    }
  }
}
